/*
@file: calculator.cpp
@author: ZZH
@date: 2022-05-05
@info: 计算组件
*/
#include "calculator.h"
#include "bufferAllocator.h"
#include "ast.h"

bool Calculator_t::allocArgs()
{
    if (nullptr != this->pListOfT)
        BufferAllocator::freeBuffer(this->pListOfT);

    this->pListOfT = BufferAllocator::getBuffer<CalculatorConf::BasicType>(
        this->getTotolPoint() * conf.getBasicTypeSize());

    if (nullptr == this->pListOfT)
        return false;

    for (size_t i = 0; i < this->totolPoint; i++) this->pListOfT[i] = i / this->fs;

    return true;
}

void Calculator_t::cleanArgs(void)
{
    if (nullptr != this->pListOfT)
        BufferAllocator::freeBuffer(this->pListOfT);

    this->pListOfT = nullptr;
}

bool Calculator_t::calculate(ASTExpress_t* exp, BasicType* pRes)
{
    bool res = false;

    try {
        if (false == this->allocArgs()) // 分配计算资源
            return false;

        exp->calculate(pRes); // 根节点递归计算语法树的值
        res = true;
    } catch (const std::exception& e) {
        UI_ERROR("calculate exception: %s", e.what());
    } catch (...) {
        UI_ERROR("catched unknow exception");
    }

    this->cleanArgs(); // 释放计算资源

    return res;
}
